<?php
	include('nusoap.php');
	class samanpayment extends PaymentModule {

		private $_html = '';
		private $_postErrors = array();
		private $_ResNum;
		private $_RefNum;
		private $_TotalAmount;
		private $_Payment;
		private $_MerchentID;
		private $_Password;
		private $_WebMethodURL;
		private $_testMode;

		function __construct() {
			$this->name = 'samanpayment';
			$this->author = 'M.Razavi';
			$this->tab = 'payments_gateways';
			$this->version = '1.2.0';

			$this->currencies = true;
			$this->currencies_mode = 'radio';


			parent::__construct(); // The parent construct is required for translations

			$this->page = basename(__FILE__, '.php');
			$this->displayName = $this->l('saman payment');
			$this->description = $this->l('saman payment module');

			$this->confirmUninstall = $this->l('Are you sure, you want to delete your details?');

			if ($_SERVER['SERVER_NAME'] == 'localhost')
				$this->warning = $this->l('You are in localhost, Saman bank can\'t validate your orders.');

			$version_mask = explode('.', _PS_VERSION_, 2);
			$version_test = $version_mask[0] > 0 && $version_mask[1] > 3;
			if (!$version_test)
			{
				$this->warning = $this->l('This module writen for prestashop 1.4.x and dosen`t work with others.');
			}


			$config = Configuration::getMultiple(array($this->name . '_merchentid', ''));
			if (!isset($config[$this->name . '_merchentid']))
				$this->warning = $this->l('Your Merchent ID must be configured in order to use this module');

			$config = Configuration::getMultiple(array($this->name . '_password', ''));
			if (!isset($config[$this->name . '_password']))
				$this->warning = $this->l('Your Password must be configured in order to use this module');

			$this->_MerchentID = Configuration::get($this->name . '_merchentid');
			$this->_Password = Configuration::get($this->name . '_password');
			$this->_WebMethodURL = 'https://Acquirer.sb24.com/ref-payment/ws/ReferencePayment?WSDL';

			$this->_testMode=false;
		}

		/**
		* 	Function install()
		* 	Is called when 'Install' in on this module within administration page
		*/
		public function install() {
			if (!parent::install()
			OR !$this->createPaymenttbl() //calls function to create payment card table
			OR !$this->registerHook('invoice')
			OR !$this->registerHook('payment')
			OR !$this->registerHook('paymentReturn')
			OR !Configuration::updateValue($this->name . '_merchentid', '')
			OR !Configuration::updateValue($this->name . '_password', '')
			)
				return false;
			return true;
		}

		public function uninstall() {
			if (!Configuration::deleteByName($this->name . '_merchentid')
			OR !Configuration::deleteByName($this->name . '_password')
			OR !parent::uninstall())
				return false;
			return true;
		}

		public function getContent() {
			if (Tools::isSubmit('submit')) {
				Configuration::updateValue($this->name . '_merchentid', Tools::getValue('samanpayment_merchentid'));
				Configuration::updateValue($this->name . '_password', Tools::getValue('samanpayment_password'));
			}

			$this->_displayForm();

			return $this->_html;
		}

		private function _displayForm() {
			$this->_html .= '
			<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
			<label>' . $this->l('Merchent ID') . '</label>
			<div class="margin-form">
			<input type="text" name="samanpayment_merchentid" value="' . Configuration::get($this->name . '_merchentid') . '"/>
			</div>
			</br>
			<label>' . $this->l('Password') . '</label>
			<div class="margin-form">
			<input type="text" name="samanpayment_password" value="' . Configuration::get($this->name . '_password') . '"/>
			</div>
			<input type="submit" name="submit" value="' . $this->l('Update') . '" class="button" />
			</form>';
		}

		private function createPaymenttbl() {
			/*         * Function called by install -
			* creates the "order_paymentcard" table required for storing payment card details
			* Column Descriptions: id_payment the primary key. 
			* id order: Stores the order number associated with this payment card
			* cardholder_name: Stores the card holder name
			* cardnumber: Stores the card number
			* expiry date: Stores date the card expires
			*/

			$db = Db::getInstance();
			/* $query = "CREATE TABLE `"._DB_PREFIX_."order_paymentcard` (
			`id_payment` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
			`id_order` INT NOT NULL ,
			`cardholdername` TEXT NOT NULL ,
			`cardnumber` TEXT NOT NULL
			) ENGINE = MYISAM "; */

			$sQuery = "CREATE TABLE `" . _DB_PREFIX_ . "module_samanpayment` (
			`id` INT(10) NOT NULL AUTO_INCREMENT,
			`res_num` CHAR(20) NOT NULL,
			`ref_num` CHAR(20) NOT NULL,
			`total_amount` INT NOT NULL,
			`payment` INT NOT NULL DEFAULT 0,
			`time_start` INT(12) NOT NULL,
			`cart_id` INT(10) NULL,
			`customer_id` INT(10) NULL,
			`order_id` INT(10) NULL,
			primary key(id),
			unique(res_num),
			index(ref_num)) ENGINE = MYISAM COLLATE utf8_general_ci";

			$db->Execute($sQuery);

			return true;
		}

		/**
		* hookPayment($params)
		* Called in Front Office at Payment Screen - displays user this module as payment option
		*/
		public function hookPayment($params) {
			global $smarty;

			$smarty->assign(array(
			'this_path' => $this->_path,
			'this_path_ssl' => Configuration::get('PS_FO_PROTOCOL') . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . "modules/{$this->name}/"));

			return $this->display(__FILE__, 'payment.tpl');
		}

		public function hookPaymentReturn($params) {
			if (!$this->active)
				return;

			return $this->display(__FILE__, 'confirmation.tpl');
		}

		/*
		* This function will check display the card details form payment_execution.tpl
		* It will check if the submit button on the form has been pressed and submit the card details to the database
		*/

		public function execPayment($cart) {
			$purchase_currency = $this->GetCurrency();
			if ($cookie->id_currency == $purchase_currency->id)
				$PurchaseAmount = number_format($cart->getOrderTotal(true, 3), 0, '', '');
			else
				$PurchaseAmount= number_format(Tools::convertPrice($cart->getOrderTotal(true, 3), $purchase_currency), 0, '', '');

			global $smarty;

			$this->_ResNum = $this->createResNum();
			$this->_TotalAmount = $cart->getOrderTotal(true, 3);

			$saveResult = $this->saveOrderInfo($this->_ResNum, $cart->getOrderTotal(true, 3));

			$smarty->assign(array(
			'Amount' => $this->_TotalAmount,
			'MID' => Configuration::get($this->name . '_merchentid'),
			'ResNum' => $this->_ResNum,
			'RedirectURL' => (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . 'modules/samanpayment/validation.php',
			'this_path' => $this->_path,
			'this_path_ssl' => Configuration::get('PS_FO_PROTOCOL') . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . "modules/{$this->name}/"));
			
			return $this->display(__FILE__, 'payment_execution.tpl');

			/*
			$post_data['Amount'] = $cart->getOrderTotal(true, 3);
			$post_data['MID'] = Configuration::get($this->name.'_merchentid');
			$post_data['ResNum'] = $this->ResNum;
			$post_data['RedirectURL'] = (Configuration::get('PS_SSL_ENABLED') ?'https://' :'http://').$_SERVER['HTTP_HOST'].__PS_BASE_URI__.'modules/samanpayment/validation.php';



			$form  = "<SCRIPT LANGUAGE=\"JavaScript\">function fnSubmit() {  document.sendparams.submit();}setTimeout(\"fnSubmit()\",10);</SCRIPT>";
			//$form .= "<body onLoad=\"document.forms['sendparams'].submit();\" >";
			$form .= "<form name=\"sendparams\" method=\"POST\" action=\"$this->action\" enctype=\"application/x-www-form-urlencoded\" >\n";
			foreach ( $this->style as $key=>$val ) {
			if( $val != '' ) {
			$form .= "<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
			}
			}
			$form .= "<input type=\"hidden\" name=\"Amount\" value=\"$post_data['Amount']\" />\n";
			$form .= "<input type=\"hidden\" name=\"ResNum\" value=\"$post_data['ResNum']\" />\n";
			$form .= "<input type=\"hidden\" name=\"MID\" value=\"$post_data['MID']\" />\n";
			$form .= "<input type=\"hidden\" name=\"RedirectURL\" value=\"$post_data['RedirectURL']\" />\n";
			$form .= "</form>";
			//$form .= "</body>";
			//$form .= "</frame>";

			return  $form; */
		}

		public function hookInvoice($params) {
			$id_order = $params['id_order'];

			global $smarty;
			$onlinePaymentDetails = $this->readOnlinePaymentDetails($id_order);
			if($onlinePaymentDetails)
			{
				$onlinePaymentDetails['time_start'] = date("Y-m-d-H:i:s",$onlinePaymentDetails['time_start']);

				$smarty->assign(array(
				'ref_num ' => $onlinePaymentDetails['ref_num '],
				'timeStart' => $onlinePaymentDetails['time_start'],
				'paymentAmount' => $onlinePaymentDetails['payment'],
				'id_order' => $id_order,
				'this_page' => $_SERVER['REQUEST_URI'],
				'this_path' => $this->_path,
				'this_path_ssl' => Configuration::get('PS_FO_PROTOCOL') . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . "modules/{$this->name}/"));
				return $this->display(__FILE__, 'invoice_saman.tpl');
			}
			else
			{
				return false;
			}
		}

		protected function saveOrderInfo($ResNum, $totalAmount) {
			/* if( $totalAmont == '' ) {
			$this->setMsg( "Error: TotalAmont" );
			return false;
			} */
			$time = time();
			//$this->totalAmont = $totalAmont;
			//$this->createResNum();

			$db = Db::getInstance(); 
			$sQuery = "INSERT INTO " . _DB_PREFIX_ . "module_samanpayment (res_num, total_amount, time_start) VALUES('$ResNum', '$totalAmount', $time);";
			return $db->Execute($sQuery);
		}

		protected function saveBankInfo($payment) 
		{
			$db = Db::getInstance();
			$sQuery = " UPDATE " . _DB_PREFIX_ . "module_samanpayment SET ref_num = '" . $this->_RefNum . "' ,payment = '$payment' WHERE res_num = '" . $this->_ResNum . "'";
			$rsQueryUpdate = $db->Execute($sQuery);
			if($rsQueryUpdate)
			{
				return $rsQueryUpdate;
			}
			else
			{
				exit();
			}
		}

		private function readOnlinePaymentDetails($intOrderID) {
			$db = Db::getInstance();
			$result = $db->ExecuteS("SELECT * FROM `" . _DB_PREFIX_ . "module_mellipayment` WHERE `order_id` =".intval($intOrderID).";");
			if (!$result) 
			{
				return false;
			}
			return $result[0];
		}

		public function createResNum()
		{
			$db = Db::getInstance();
			$resNum = 0;
			do {
				$m = "777".microtime(true);
				$resNum = substr($m, 0, 12);
				// $m = md5(microtime());
				// $resNum = substr($m, 0, 20);
				$search = $db->ExecuteS("SELECT res_num FROM `" . _DB_PREFIX_ . "module_samanpayment` WHERE res_num = '$resNum'");
				if (empty($search)) {
					break;
				}
			} while (true);

			$this->_ResNum = $resNum;

			return $resNum;
		}

		public function checkErrorState($State, $ResNum, $RefNum, $errorMessage='', $displayErrorMessage=false) {
			$this->_postErrors[] = $this->l("ST-ERR-Error in transaction\npayment not complete");
			//$this->_postErrors[] = $this->l("State=$State; RefNum=$RefNum; ResNum=$ResNum; \nST-ERR-Error in transaction\npayment not complete");
			//$db = Db::getInstance();
			//			$result = $db->ExecuteS("select * FROM " . _DB_PREFIX_ . "module_samanpayment where res_num = $ResNum");
			//			if($result)
			//				foreach ($result AS $item)
			//					$this->_postErrors[] = $this->l($item['total_amount']." ".$result[0]['total_amount'] );
			if (!$displayErrorMessage) 
			{
				if (empty($RefNum))
					$this->_postErrors[] = $this->l('ST-ERR-RefNum is empty');
				if (empty($ResNum))
					$this->_postErrors[] = $this->l('ST-ERR-Resnum is emphty');

				$this->_postErrors[] = $this->l($State);
				//switch($_POST['State'])
				switch ($State) 
				{
					case 'Canceled By User' :
						$this->_postErrors[] = $this->l('ST-ERR-Canceled By User');
						//ERROR("تراکنش توسط خريدار کنسل شده است.");
						break;
					case 'Invalid Amount' :
						$this->_postErrors[] = $this->l('ST-ERR-Invalid Amount');
						//ERROR("مبلغ سند برگشتي، از مبلغ تراکنش اصلي بيشتر است.");
						break;
					case 'Invalid Transaction' :
						$this->_postErrors[] = $this->l('ST-ERR-Invalid Transaction');
						//ERROR("درخواست برگشت يک تراکنش رسيده است، در حالي که تراکنش اصلي پيدا نمي شود.");
						break;
					case 'Invalid Card Number' :
						$this->_postErrors[] = $this->l('ST-ERR-Invalid Card Number');
						//ERROR("شماره کارت اشتباه است.");
						break;
					case 'No Such Issuer' :
						$this->_postErrors[] = $this->l('ST-ERR-No Such Issuer');
						//ERROR("چنين صادر کننده کارتي وجود ندارد.");
						break;
					case 'Expired Card Pick Up' :
						$this->_postErrors[] = $this->l('ST-ERR-Expired Card Pick Up');
						//ERROR("از تاريخ انقضاي کارت گذشته است و کارت ديگر معتبر نيست.");
						break;
					case 'Allowable PIN Tries Exceeded Pick Up' :
						$this->_postErrors[] = $this->l('ST-ERR-Allowable PIN Tries Exceeded Pick Up');
						//ERROR("رمز کارت (PIN) 3 مرتبه اشتباه وارد شده است در نتيجه کارت غير فعال خواهد شد.");
						break;
					case 'Incorrect PIN' :
						$this->_postErrors[] = $this->l('ST-ERR-Incorrect PIN');
						//ERROR("خريدار رمز کارت (PIN) را اشتباه وارد کرده است.");
						break;
					case 'Exceeds Withdrawal Amount Limit' :
						$this->_postErrors[] = $this->l('ST-ERR-Exceeds Withdrawal Amount Limit');
						//ERROR("مبلغ بيش از سقف برداشت مي باشد.");
						break;
					case 'Transaction Cannot Be Completed' :
						$this->_postErrors[] = $this->l('ST-ERR-Transaction Cannot Be Completed');
						//ERROR("تراکنش Authorize شده است ( شماره PIN و PAN درست هستند) ولي امکان سند خوردن وجود ندارد.");
						break;
					case 'Response Received Too Late' :
						$this->_postErrors[] = $this->l('ST-ERR-Response Received Too Late');
						//ERROR("تراکنش در شبکه بانکي Timeout خورده است.");
						break;
					case 'Suspected Fraud Pick Up' :
						$this->_postErrors[] = $this->l('ST-ERR-Suspected Fraud Pick Up');
						//ERROR("خريدار يا فيلد CVV2 و يا فيلد ExpDate را اشتباه زده است. ( يا اصلا وارد نکرده است)");
						break;
					case 'No Sufficient Funds' :
						$this->_postErrors[] = $this->l('ST-ERR-No Sufficient Funds');
						//ERROR("موجودي به اندازي کافي در حساب وجود ندارد.");
						break;
					case 'Issuer Down Slm' :
						$this->_postErrors[] = $this->l('ST-ERR-Issuer Down Slm');
						//ERROR("سيستم کارت بانک صادر کننده در وضعيت عملياتي نيست.");
						break;
					case 'TME Error' :
						$this->_postErrors[] = $this->l('ST-ERR-TME Error');
						//ERROR("خطا ايجاد شده قابل شناسايى نيست. لطفا با مديريت سايت تماس بگيريد");
						break;
					default :
						$this->_postErrors[] = $this->l($State);
						//ERROR("خطا ايجاد شده قابل شناسايى نيست. لطفا با مديريت سايت تماس بگيريد");
						break;
				}
			} 
			else 
			{
				$this->_postErrors[] = $this->l($errorMessage);
			}

			$this->displayErrors();
			echo $this->_html;
			return $result;
		}

		public function checkErrorVerify($errorCode) 
		{
			switch ($errorCode) 
			{
				case '-1' :
					$this->_postErrors[] = $this->l('VRF-ERR-خطای داخلی شبکه');
					break;
				case '-2' :
					$this->_postErrors[] = $this->l('VRF-ERR-سپرده ها برابر نیستند');
					break;
				case '-3' :
					$this->_postErrors[] = $this->l('VRF-ERR-ورودی ها حاوی کاراکترهای غیر مجاز میباشد');
					break;
				case '-4' :
					$this->_postErrors[] = $this->l('VRF-ERR-کلمه عبور یا کد فروشنده اشتباه است');
					break;
				case '-5' :
					$this->_postErrors[] = $this->l('VRF-ERR-خطای بانک اطلاعاتی');
					break;
				case '-6' :
					$this->_postErrors[] = $this->l('VRF-ERR-سند قبلا برگشت کامل خورده');
					break;
				case '-7' :
					$this->_postErrors[] = $this->l('VRF-ERR-رسید دیجیتالی تهی است');
					break;
				case '-8' :
					$this->_postErrors[] = $this->l('VRF-ERR-خطای طول ورودی ها بیشتر از حد مجاز است');
					break;
				case '-9' :
					$this->_postErrors[] = $this->l('VRF-ERR-وجود کارکترهای غیر مجاز در مبلغ برگشتی');
					break;
				case '-10' :
					$this->_postErrors[] = $this->l('VRF-ERR-رسید دیجیتالی حاوی کارکترهای غیر مجاز است');
					break;
				case '-11' :
					$this->_postErrors[] = $this->l('VRF-ERR-طول ورودی ها کمتر از حد مجاز است');
					break;
				case '-12' :
					$this->_postErrors[] = $this->l('VRF-ERR-مبلغ برگشتی منفی است');
					break;
				case '-13' :
					$this->_postErrors[] = $this->l('VRF-ERR-مبلغ برگشتی برای برگشت جزیی بیش از مبلغ برگشت نخورده رسید دیجیتالی است');
					break;
				case '-14' :
					$this->_postErrors[] = $this->l('VRF-ERR-چنین تراکنشی تعریف نشده است');
					break;
				case '-15' :
					$this->_postErrors[] = $this->l('VRF-ERR-مبلغ برگشتی به صورت اعشاری داده شده');
					break;
				case '-16' :
					$this->_postErrors[] = $this->l('VRF-ERR-خطای داخلی سیستم');
					break;
				case '-17' :
					$this->_postErrors[] = $this->l('VRF-ERR-برگشت زدن تراکنشی که با کارت بانکی غیر از بانک سامان انجام شده');
					break;
				case '-18' :
					$this->_postErrors[] = $this->l('VRF-ERR-فروشنده نامعتبر است ip address');
					break;
			}

			$this->displayErrors();
			echo $this->_html;
			return $result;
		}

		public function displayErrors() 
		{
			foreach ($this->_postErrors AS $err)
				$this->_html .= '<div class="alert error">' . $err . '</div>';
		}

		public function searchResNum($resNum) 
		{
			$db = Db::getInstance();
			$result = $db->ExecuteS("SELECT * FROM `" . _DB_PREFIX_ . "module_samanpayment` WHERE `res_num` = '$resNum'");
			return $result;
		}

		public function searchRefNum($refNum) 
		{
			$db = Db::getInstance();
			$result = $db->ExecuteS("select * FROM `" . _DB_PREFIX_ . "module_samanpayment` WHERE ref_num = '$refNum'");
			return $result;
		}

		public function lastCheck($ResNum, $RefNum) 
		{
			if (empty($ResNum) or strlen($RefNum) != 20) 
			{
				$this->_postErrors[] = $this->l('Error: resNum or refNum is empty');
				//$this->setMsg( "Error: resNum or refNum is empty" );
				return false;
			}

			$this->_ResNum = $ResNum;
			$this->_RefNum = $RefNum;
			$searchResult = $this->searchResNum($ResNum);   
			$this->_TotalAmount = $searchResult[0]['total_amount'];

			//web method verify transaction
			$verify = $this->verifyTrans();
			//$verify = $this->_TotalAmount;
			//$this->_postErrors[] = $this->l("TotalAmount=".$this->_TotalAmount."; RefNum=$RefNum; ResNum=$ResNum; \nST-ERR-Error in transaction\npayment not complete");
			//$strErrorgetMsgError()


			//###########################################################################################################################

			if ($verify > 0) 
			{
				if ($verify == $this->_TotalAmount) 
				{
					$_Payment = $verify;
					$this->saveBankInfo($verify);
					$this->_postErrors[] = $this->l("Payment successful.");
					//$this->setMsg("پرداخت با موفقیت انجام شد  لطفا کد رهگیری را یادداشت کنید");
					//$this->setMsg( "$this->resNum"." : کد رهگیری " );
					return true;
				} 
				elseif ($verify > $this->_TotalAmount) 
				{
					//web method partial reverse transaction
					$revAmont = $verify - $this->_TotalAmount;
					$reverse = $this->reverseTrans($revAmont);

					$this->_postErrors[] = $this->l("Payment is more than total amount.");
					//$this->setMsg("کاربر گرامی  مبلغ پرداختی بیش از مبلغ درخواستی است");
					if ($reverse == 1) 
					{
						$this->_postErrors[] = $this->l("remainder amount is reversed to your account.");
						//$this->setMsg("مابقی مبلغ پرداخت شده به حساب شما برگشت خورده");
						$this->saveBankInfo($this->_TotalAmount);
					} 
					else 
					{
						$this->checkErrorVerify($reverse);
						$this->_postErrors[] = $this->l("remainder amount will reversed to your account in future.");
						//$this->setMsg( "ما بقی مبلغ پرداختی شما در اینده ای نزدیک به حساب شما برگشت خواهد خورد " );
						$this->saveBankInfo($verify);
					}
					//$this->setMsg("پرداخت با موفقیت انجام شد  لطفا کد رهگیری را یادداشت کنید");
					//$this->setMsg( "$this->resNum"." : کد رهگیری " );
					return true;
				} 
				elseif ($verify < $this->_TotalAmount) 
				{

					//web method full reverse transaction
					$rev = $this->reverseTrans($verify);
					$this->_postErrors[] = $this->l("Payment is less than total amount.");
					//$this->setMsg("مبلغ پرداختی شما کمتر از مبلغ سفارش است ");
					if ($rev == 1) 
					{
						$this->_postErrors[] = $this->l("Paymnet amount is reversed to your account.");
						//$this->setMsg("کل مبلغ پرداختی به حساب شما برگشت خورده");
						$this->saveBankInfo(0);
					} 
					else 
					{
						$this->_postErrors[] = $this->l("Paymnet amount will reversed to your account in future.");
						//$this->setMsg("در اینده ای نزدیک کل مبلغ پرداختی به حساب شما برگشت خواهد خورد لطفا برای پی گیری کد رهگیری را یادداشت کنید");
						//$this->setMsg( "$this->resNum"." : کد رهگیری " );
						$this->checkErrorVerify($rev);
						$this->saveBankInfo($verify);
					}
					$this->displayErrors();
					echo $this->_html;

					return false;
				}
				//Error transaction
			}
			elseif ($verify < 0 or $verify == false) 
			{
				$this->_postErrors[] = $this->l("Error in Verify Payment");
				//$this->setMsg( "کاربر گرامی مشکلی در تایید  پرداخت پیش امده" );
				$this->checkErrorVerify($verify);
				$this->saveBankInfo(0);

				$this->displayErrors();
				echo $this->_html;

				return false;
			}

			$this->displayErrors();
			echo $this->_html;
			return false;
		}

		protected function verifyTrans() {
			if (empty($this->_RefNum) or empty($this->_MerchentID)) {
				return false;
			}

			//die($this->_WebMethodURL."-".'wsdl');      
			//$soapClient = new soapclient($this->_WebMethodURL,'wsdl');
			$soapclient = new nusoap_client('https://Acquirer.sb24.com/ref-payment/ws/ReferencePayment?WSDL','wsdl');

			$soapProxy = $soapclient->getProxy();
			$result = false;

			for ($a = 1; $a < 7; ++$a) 
			{
				$result = $soapProxy->verifyTransaction($this->_RefNum, $this->_MerchentID);
				if ($result != false) 
				{
					break;
				}
			}
			return $result;
		}

		protected function reverseTrans($revNumber) {
			if ($revNumber <= 0 or empty($this->_RefNum) or empty($this->_MerchentID) or empty($this->_Password)) {
				return false;
			}
			$soapClient = new soapclient($this->_WebMethodURL, 'wsdl');
			$soapProxy = $soapClient->getProxy();
			$result = false;

			for ($a = 1; $a < 7; ++$a) {
				$result = $soapProxy->reverseTransaction($this->_RefNum, $this->_MerchentID, $this->_Password, $revNumber);
				if ($result != false)
					break;
			}
			return $result;
		}

	}
?>
